package com.example.esspringbootrestclientdome.controller;

import com.example.esspringbootrestclientdome.config.Config;
import com.example.esspringbootrestclientdome.config.ElasticSearchConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController("es.testController")
@RequestMapping("/es/tc")
public class TestController {
    @Autowired
    Config config;
    /**
     * jackson的objectMappert
     */
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private RestHighLevelClient client;

    //保存数据
    @RequestMapping("saveData")
    public String saveData() throws IOException {
        //指定索引和id
        IndexRequest request = new IndexRequest(config.getIndex());
        //request.opType(DocWriteRequest.OpType.CREATE);

        //如果id存在则修改
        request.id("1");

        //数据转为json格式
        Map<String, Object> user = new HashMap<>();
        user.put("id", "3");
        user.put("nm", "zheng");
        user.put("sex", "男");
        user.put("age", 19);
        user.put("text", "我爱中华");
        String userString = objectMapper.writeValueAsString(user);
        request.source(userString, XContentType.JSON);

        //简写
        //IndexRequest request = new IndexRequest("my_index").id("1").source(userString,XContentType.JSON);

        //执行保存操作
        IndexResponse indexResponse = client.index(request, ElasticSearchConfig.COMMON_OPTIONS);

        System.out.println(indexResponse);
        return indexResponse.toString();
    }

    //复杂检索数据
    @RequestMapping("searchData")
    public void searchData() throws IOException {
        String index = "my_index";
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices(index);
        //指定DSL，检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //1.1 构造检索条件
        //address中包含mill
        searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));
        //按照前10种年龄分布进行聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(ageAgg);
        //求所有人年龄的平均值
        AvgAggregationBuilder ageAvg = AggregationBuilders.avg("ageAvg").field("age");
        searchSourceBuilder.aggregation(ageAvg);

        System.out.println(searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);


        //2.执行检索
        SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //3.分析结果
        //3.1 查看查询结果
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            System.out.println(hit);
        }
        //3.2 查看聚合结果
        Aggregations aggs = searchResponse.getAggregations();

        Terms ageAgg2 = aggs.get("ageAgg");
        for (Terms.Bucket bucket : ageAgg2.getBuckets()) {
            System.out.println("年龄：" + bucket.getKeyAsString() + "==> 人数：" + bucket.getDocCount());
        }
        System.out.println();

        Avg ageAvg2 = aggs.get("ageAvg");
        System.out.println("平均年龄：" + ageAvg2.getValue());
    }

    //高亮
    @RequestMapping("sh")
    public String searchHighlight() throws IOException {
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices(config.getIndex());
        //指定DSL，检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchQuery("text", "我"));

        HighlightBuilder highlightBuilder = new HighlightBuilder(); //创建一个新的HighlightBuilder。
        HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("text");  //为title字段创建字段高光色。
        highlightTitle.highlighterType("unified"); // 设置字段高光色类型。
        highlightBuilder.field(highlightTitle);   //将字段高光色添加到高亮构建器。
        /*HighlightBuilder.Field highlightUser = new HighlightBuilder.Field("我");
        highlightBuilder.field(highlightUser);*/
        searchSourceBuilder.highlighter(highlightBuilder);

        System.out.println(searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);

        //2.执行检索
        SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

        System.out.println(searchResponse);
        System.out.println(searchResponse.toString());

        return searchResponse.toString();
    }
}
